<template>
  <div class="querylog-container">
    <div class="header">
      <h2>查询日志</h2>
      <div class="time-filter">
        <span>当前模拟时间：</span>
        <el-tag type="info">{{ formattedTime }}</el-tag>
        <el-button
            type="primary"
            size="small"
            :icon="Refresh"
            style="margin-left: 10px"
            @click="reloadCurrentView"
        >
          刷新
        </el-button>
      </div>
    </div>

    <div class="query-container">
      <span>起止时间：</span>
      <el-date-picker
          v-model="queryParams.timeRange"
          :default-value="defaultTimeRange"
          :default-time="defaultTimeRange"
          :clearable="false"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :disabled-date="disableFutureDates"
          :disabled-hours="disableFutureHours"
          :disabled-minutes="disableFutureMinutes"
          :disabled-seconds="disableFutureSeconds"
          style="width: 300px; margin-right: 10px"
      />
      <span>查询类型：</span>
      <el-input
          v-model="queryParams.query_type"
          placeholder="请输入查询类型"
          clearable
          style="width: 150px; margin-right: 10px"
      />
      <el-button type="primary" @click="fetchData">查询</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </div>

    <el-table
        :data="paginatedData"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        height="calc(100vh - 220px)"
        @sort-change="handleSortChange"
    >
      <el-table-column
          prop="QUERY_LOG_ID"
          label="日志ID"
          align="center"
          sortable="custom"
      />
      <el-table-column
          prop="QUERY_TYPE"
          label="查询类型"
          align="center"
          sortable="custom"
      >
        <template #default="{row}">
          <el-tag :type="getTagType(row.QUERY_TYPE)">
            {{ row.QUERY_TYPE }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="QUERY_TIME"
          label="查询时间"
          align="center"
          sortable="custom"
      />
      <el-table-column
          prop="QUERY_SPEND_TIME"
          label="查询耗时"
          align="center"
          sortable="custom"
      >
      <template #default="{row}">
        <span :class="getQueryTimeClass(row.QUERY_SPEND_TIME)">{{ row.QUERY_SPEND_TIME }}</span>
      </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right">
        <template #default="{row}">
          <el-button type="text" size="small" @click="showSQLDetail(row)">查看SQL</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="true"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="queryLogData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- SQL详情对话框 -->
    <el-dialog v-model="sqlDetailVisible" title="SQL详情" width="70%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="SQL语句">
          <div class="sql-content">{{ currentQuery }}</div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="sqlDetailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { useSimulationStore } from '@/store/simulation'
import { storeToRefs } from "pinia"
import { ElMessage } from "element-plus"
import axios from "axios";

const simulationStore = useSimulationStore()
const { formattedTime,initialTime,currentTime } = storeToRefs(simulationStore)
const {formatDateTime} = simulationStore
// 表格数据
const queryLogData = ref([])
const loading = ref(false)
const sqlDetailVisible = ref(false)
const currentQuery = ref()

// 查询参数
const queryParams = ref({
  timeRange:[
      initialTime.value,
      currentTime.value,
  ],
  query_type: '',
  query_spend_time: '',
})


// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
})

// 排序参数
const sortParams = ref({
  prop: '',
  order: ''
})


// 默认时间范围
const defaultTimeRange = ref([
  initialTime.value,
  currentTime.value
])
// 时间规则
const disableFutureDates = (time: Date) => {
  return time > currentTime.value || time < initialTime.value
}
const disableFutureHours = () => {
  const now = currentTime.value
  return Array.from({length: 24}, (_, i) => i)
      .filter(h => h > now.getHours())
}
const disableFutureMinutes = (selectedHour: number) => {
  const now = currentTime.value
  if (selectedHour > now.getHours()) {
    return Array.from({length: 60}, (_, i) => i)
  }
  return Array.from({length: 60}, (_, i) => i)
      .filter(m => m > now.getMinutes())
}
const disableFutureSeconds = (selectedHour: number, selectedMinute: number) => {
  const now = currentTime.value
  if (selectedHour > now.getHours() ||
      (selectedHour === now.getHours() && selectedMinute > now.getMinutes())) {
    return Array.from({length: 60}, (_, i) => i)
  }
  return Array.from({length: 60}, (_, i) => i)
      .filter(s => s > now.getSeconds())
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      start_time:formatDateTime(queryParams.value.timeRange[0]),
      end_time:"2026-01-01 00:00:00",
      query_spend_time:queryParams.value.query_spend_time,
      query_type:queryParams.value.query_type
    }
    const response = await axios.get('http://localhost:5000/query_logs', { params })
    if(!response.data.data){
      ElMessage.warning("未查询到相关信息！")
      return
    }
    queryLogData.value = response.data.data.logs
    // 排序数据
    if (sortParams.value.prop && sortParams.value.order) {
      queryLogData.value.sort((a, b) => {
        const valueA = a[sortParams.value.prop]
        const valueB = b[sortParams.value.prop]
        if (sortParams.value.order === 'ascending') {
          return valueA > valueB ? 1 : -1
        } else {
          return valueA < valueB ? 1 : -1
        }
      })
    }

  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 计算分页后的数据
const paginatedData = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return queryLogData.value.slice(start, end)
})

// 标签颜色类型
const tagTypes = ['', 'success', 'warning', 'danger', 'info']
// 存储已分配的标签颜色
const tagColorMap = new Map()
// 获取随机标签类型
const getTagType = (tagName: string) => {
  if (!tagName) return ''

  // 如果已经分配过颜色，直接返回
  if (tagColorMap.has(tagName)) {
    return tagColorMap.get(tagName)
  }

  // 随机分配一个颜色类型
  const randomType = tagTypes[Math.floor(Math.random() * tagTypes.length)]
  tagColorMap.set(tagName, randomType)
  return randomType
}
// 根据查询耗时获取样式类
const getQueryTimeClass = (time: number) => {
  if (time > 1000) return 'slow-query'
  if (time > 500) return 'medium-query'
  return 'fast-query'
}

// 显示SQL详情
const showSQLDetail = (row: any) => {
  currentQuery.value = row.QUERY_SQL,
  sqlDetailVisible.value = true
}

// 处理排序
const handleSortChange = ({ prop, order }) => {
  sortParams.value = { prop, order }
  fetchData()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val
}

// 重置查询
const resetQuery = async() => {
  queryParams.value = {
    timeRange:[
      initialTime.value,
      currentTime.value,
    ],
    query_type: '',
    query_spend_time: '',
  }
  sortParams.value = {
    prop: '',
    order: ''
  }
  await fetchData()
}

// 重新加载界面
const reloadCurrentView = async() => {
  await resetQuery()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.querylog-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.time-filter {
  display: flex;
  align-items: center;
}

.query-container {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

/* 查询耗时样式 */
.fast-query {
  color: #67C23A;
}

.medium-query {
  color: #E6A23C;
}

.slow-query {
  color: #F56C6C;
  font-weight: bold;
}

.sql-content {
  white-space: pre-wrap;
  font-family: monospace;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

</style>